package com._21cn.cms.resource.web.servlet;

import com._21cn.cms.resource.utils.UploadHelper;
import com._21cn.cms.resource.utils.upload.UploadHandler;
import com._21cn.framework.utils.StringUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * User: 司徒海富 2017-03-26
 */
@MultipartConfig(location = "/tmp", fileSizeThreshold = 5242880, maxFileSize = 52428800)
public class CommonFileUploadServlet extends HttpServlet {

    private static final Logger log = LoggerFactory.getLogger(CommonFileUploadServlet.class);

    private UploadHandler uploadHandler;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        ServletContext context = servletConfig.getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(context);
        String handlerStr = servletConfig.getInitParameter("uploadHandler");
        if (StringUtil.isEmpty(handlerStr)) {
            handlerStr = "pictureUploadHandler";
        }
        uploadHandler = (UploadHandler) wac.getBean(handlerStr);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        UploadHandler handler = uploadHandler;
        if (handler != null) {
            handler.beforeUpload(request, response);                                                                            //before
            Map<UploadHelper.UploadResultType, Map<String, File>> map = handler.process(request, response);              //process
            Map<UploadHelper.UploadResultType, List<Object>> resultMap = handler.afterUpload(map, request, response);    //after
            out.println(JSON.toJSONString(resultMap, true));
        } else {
            log.error("upload handler is null");
        }
    }

}
